package fxmedia.ui;

// Import JavaFX Classes
import javafx.event.EventHandler;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

// Import Application classes
import fxmedia.Constants;
import fxmedia.FxMedia;

/**
 * @author dca
 */
public class PlayButton extends Label {
	public static enum State { PUSH_TO_PLAY, PUSH_TO_STOP };
	private State state = State.PUSH_TO_PLAY;

	/**
	 * Constructs the play button.<br/>
	 * @param app The media player application.<br/>
	 */
	public PlayButton(final FxMedia app) {
		super();
		this.setPushToPlay();
		this.setDisable(true); // This is re-enabled from LibraryList::initSelectionListener(FxMedia)
		this.initMouseClickListener(app);
	} // END constructor

	/**
	 * Adds a listener to detect mouse clicks on the play button.<br/>
	 * @param app The media player application.<br/>
	 */
	private void initMouseClickListener(final FxMedia app) {
		this.setOnMouseClicked(new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent me) {
				if(State.PUSH_TO_STOP == state || app.getPlayer().isPlaying()) {
					app.getPlayer().stop();
					setPushToPlay();
				} else if(State.PUSH_TO_PLAY == state) {
					playCurrentSelection(app);
				} // END if/else
			} // END handle
		}); // END setOnMouseClicked
	} // END initMouseClickListener

	/**
	 * plays the song that&apos;s currently highlighted in the library.<br/>
	 * Also, updates the track information within the application.<br/>
	 * @param app The media player application.<br/>
	 */
	public void playCurrentSelection(final FxMedia app) {
		if(null != app) {
			app.getPlayer().play(app);
			setPushToStop();
		} // END if
	} // END playCurrentSelection

	public State getState() {
		return state;
	} // END getState

	private void setPushToPlay() {
		state = State.PUSH_TO_PLAY;
		setGraphic(new ImageView(new Image(FxMedia.class.getResourceAsStream(Constants.PLAY_TRACK_IMAGE_PATH))));
	} // END setPushToPlay

	private void setPushToStop() {
		state = State.PUSH_TO_STOP;
		setGraphic(new ImageView(new Image(FxMedia.class.getResourceAsStream(Constants.STOP_TRACK_IMAGE_PATH))));
	} // END setPushToStop
} // END class PlayButton
